package cn.com.bsoft.wePortal.partner.utils

import cn.com.bsoft.kotlinEx.javaType
import cn.com.bsoft.kotlinEx.objectMapper
import cn.com.bsoft.kotlinEx.post
import cn.com.bsoft.kotlinEx.sha265
import org.apache.http.HttpHeaders
import java.net.URL
import java.util.*

inline fun <reified T:Any> URL.ajax(obj:Any?,partnerCode:String,secret:String):T?{
    val now = Date().time/1000
    val body = objectMapper().writeValueAsString(obj)
    val request = "$body$secret$now"
    val sign = request.toByteArray(Charsets.UTF_8).sha265()

    val input = post({
        out ->
        out.write(body.toByteArray(Charsets.UTF_8))
    },{httpPost ->
        httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
        httpPost.addHeader("ACCEPT", "application/json")
        httpPost.addHeader("PartnerCode",partnerCode)
        httpPost.addHeader("PartnerTimeStamp","$now")
        httpPost.addHeader("PartnerSign",sign)
    })

    val javaType = T::class.javaType

    return objectMapper().readValue(input,javaType)
}